package com.ScoresSystem.controller;

import com.ScoresSystem.pojo.Student;
import com.ScoresSystem.pojo.Subject;
import com.ScoresSystem.service.SubjectService;
import com.ScoresSystem.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/subject")
public class SubjectController {

    @Autowired
    SubjectService subjectService;


    // 分页查询所有科目
    @RequestMapping("/getAllSubject")
    public Result<List<Subject>> getAllSubject(@RequestParam(value = "name", defaultValue = "") String name,
                                               @RequestParam (value = "page", defaultValue = "1") int page,
                                               @RequestParam (value = "limit", defaultValue = "10") int limit){
        List<Subject> subjectList = subjectService.getAllSubject("%" + name + "%", (page - 1) * limit, limit);
        int count = subjectService.getCount("%" + name + "%");
        return new Result<>("0", "查询成功", subjectList, count);
    }

    // 添加科目
    @RequestMapping("/addSubject")
    public Result<String> addSubject(Subject subject){
        // 检查科目名是否存在
        Subject sub1 = subjectService.findSubjectByName(subject.getName());
        System.out.println(sub1);
        if (sub1 != null){
            return new Result<>("1", "科目已存在");
        }
        int result = subjectService.addSubject(subject);
        if (result == 1){
            return new Result<>("0", "添加成功");
        }
        return new Result<>("2", "添加失败");
    }

    // 修改学生信息
    @RequestMapping("/updateSubject")
    public Result<String> updateSubject(Subject subject){
        int result = subjectService.updateSubject(subject);
        if (result == 1){
            return new Result<>("0", "修改成功");
        }
        return new Result<>("1", "修改失败");
    }

    // 删除学生
    @RequestMapping("/deleteSubject")
    public Result<String> deleteSubject(String id){
        int result = subjectService.deleteSubject(id);
        if (result == 1){
            return new Result<>("0", "删除成功");
        }
        return new Result<>("1", "删除失败");
    }

    // 查询所有科目
    @RequestMapping("/subjectSelect")
    public Result<List<Subject>> subjectSelect(){
        List<Subject> subjectList = subjectService.subjectSelect();
        if (subjectList == null || subjectList.isEmpty()){
            return new Result<>("1", "查询失败");
        }
        return new Result<>("0", "查询成功", subjectList);
    }
}
